package cn.edu.sdjzu.xg.bysj.controller;

import cn.edu.sdjzu.xg.bysj.domain.School;
import cn.edu.sdjzu.xg.bysj.exception.BysjException;
import cn.edu.sdjzu.xg.bysj.service.SchoolService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/schoolDelete.ctl")
public class SchoolDelCtl extends HttpServlet {
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应字符编码为UTF8，以便正确响应汉字
        response.setContentType("application/json;charset=UTF-8");
        // 创建JSON对象message，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        // 如果请求body为空
        if (request == null) {
            message_jsonObj.put("message", "未收到请求信息！");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try{
            String id_str = request.getParameter("id");
            int id = Integer.parseInt(id_str);
            School school = SchoolService.getInstance().find(id);
            boolean delete = SchoolService.getInstance().delete(id);
            if (delete){
                message_jsonObj.put("message","删除成功");
            }else {
                message_jsonObj.put("message","删除失败，" + school.getDescription() + "仍有系存在");
            }
            response.getWriter().println(message_jsonObj);
        }catch (BysjException e) {
            message_jsonObj.put("message",e.getMessage());
            response.getWriter().println(message_jsonObj);
            // 每个都要有printStackTrace
            e.printStackTrace();
        }catch (SQLException e){
            message_jsonObj.put("message","数据库操作异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }catch (Exception e){
            message_jsonObj.put("message","网络异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }
    }
}
